const response = require('../../utils/response');
const { handleDatabaseError } = require('../../utils/dberrordeal');
const TagService = require('../../services/good/tagService');
class TagController {
    static async getTagList(ctx) {
        try {
            // 初始化请求数据
            const requestData = ctx.request.body || {};
            
            // 设置分页参数默认值
            const pageNum = parseInt(requestData.pageNum) || 1;
            const pageSize = parseInt(requestData.pageSize) || 10;
            
            // 构建查询数据，排除分页参数
            const queryData = { ...requestData };
            delete queryData.pageNum;
            delete queryData.pageSize;
            
            const res = await TagService.getTagList({ pageNum, pageSize }, queryData);
            response.success(ctx, { data: res });
        } catch (err) {
            handleDatabaseError(ctx, err, '获取标签列表失败');
        }
    }
    static async getTagTypeList(ctx) {
        const res = await TagService.getTagTypeList();
        res? response.success(ctx, { data: res }) : response.error(ctx, {});
    }
    static async getTagById(ctx) {
        const { id: tagId } = ctx.request.body;
        const res = await TagService.getTagById(tagId);
        res? response.success(ctx, { data: res }) : response.error(ctx, { message: '标签不存在'});
    }
    static async createTag(ctx) {
        try {
            const data = ctx.request.body;
            
            // 验证必要字段
            if (!data || !data.name || !data.type) {
                return response.error(ctx, { msg: '标签名称和类型为必填项' });
            }
            
            const res = await TagService.createTag(data);
            response.success(ctx, { data: res });
        } catch (err) {
            handleDatabaseError(ctx, err, '创建标签失败');
        }
    }

    static async updateTag(ctx) {
        try {
            const data = ctx.request.body;
            
            // 验证必要字段
            if (!data || !data.id) {
                return response.error(ctx, { msg: '标签ID为必填项' });
            }
            
            const res = await TagService.updateTag(data);
            response.success(ctx, { data: res });
        } catch (err) {
            handleDatabaseError(ctx, err, '更新标签失败');
        }
    }
    static async deleteTag(ctx) {
        try {
            const { id } = ctx.request.body;
            
            // 验证必要参数
            if (!id) {
                return response.error(ctx, { msg: '标签ID为必填项' });
            }
            
            const res = await TagService.deleteTag(id);
            response.success(ctx, { data: res });
        } catch (err) {
            handleDatabaseError(ctx, err, '删除标签失败');
        }
    }
}
module.exports = TagController;